/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package comm

import (
	"strings"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
	"github.com/pkg/errors"
)

// NetworkInodeConfig fetches the inode configuration based on a key (name or URL).
func NetworkInodeConfig(cfg ichain.EndpointConfig, key string) (*ichain.NetworkInode, error) {
	inodeCfg, ok := cfg.InodeConfig(key)
	if !ok {
		return nil, errors.Errorf("inode [%s] not found", key)
	}

	// find IAM ID
	networkInodes := cfg.NetworkInodes()

	var iamID string
	for _, inode := range networkInodes {
		if inode.URL == inodeCfg.URL { // need to use the looked-up URL due to matching
			iamID = inode.IAMID
			break
		}
	}

	np := ichain.NetworkInode{
		InodeConfig: *inodeCfg,
		IAMID:       iamID,
	}

	return &np, nil
}

// SearchInodeConfigFromURL searches for the inode configuration based on a URL.
func SearchInodeConfigFromURL(cfg ichain.EndpointConfig, url string) (*ichain.InodeConfig, error) {
	inodeCfg, ok := cfg.InodeConfig(url)

	if ok {
		return inodeCfg, nil
	}

	//If the given url is already parsed URL through entity matcher, then 'cfg.InodeConfig()'
	//may return NoMatchingInodeEntity error. So retry with network inode URLs
	networkInodes := cfg.NetworkInodes()
	for _, inode := range networkInodes {
		if inode.URL == url {
			return &inode.InodeConfig, nil
		}
	}

	return nil, errors.Errorf("unable to get inodeconfig for given url : %s", url)
}

// IAMID returns the IAM ID for the requested organization
func IAMID(cfg ichain.EndpointConfig, org string) (string, bool) {
	networkConfig := cfg.NetworkConfig()
	//check for nil since any endpointconfig implementation can be passed here
	if networkConfig == nil {
		return "", false
	}
	// viper lowercases all key maps, org is lower case
	iamID := networkConfig.Organizations[strings.ToLower(org)].IAMID
	if iamID == "" {
		return "", false
	}

	return iamID, true
}
